<template>
  <div :class="[type === 'text' ? 'dtext' : 'baseText', 'treeOrgBox', iptClass]">
    <a-icon
      v-if="!disabled && !loadingSpin"
      type="search"
      class="searchIcon"
    />
    <a-spin
      v-if="loadingSpin && !isSearchPage"
      class="searchIcon2"
      style="z-index: 99"
    >
      <a-icon
        slot="indicator"
        type="loading"
        style="font-size: 16px"
      />
    </a-spin>
    <div
      v-click-outside="out"
      style="position: relative"
    >
      <a-input
        ref="iptRefs"
        :value="text"
        :placeholder="placeholder"
        class="inpWidth"
        :disabled="disabled"
        :allow-clear="text && allowClear && !disabled"
        @change="onChange"
        @click="visible=true"
      />
      <div
        :class="[!appendToBody ? `${domClass} popC pop` : `${domClass} pop`, 'selectTree']"
        v-show="visible"
      >
        <a-spin
          v-show="!disabled"
          :spinning="spinning"
        >
          <a-row
            :gutter="[10, 0]"
            style="padding: 0 15px"
          >
            <a-col :span="12">
              <a-tooltip placement="top">
                <template slot="title">
                  <span>组织状态筛选</span>
                </template>
                <a-select
                  v-model="enable"
                  style="width: 100%"
                  placeholder="请选择组织状态"
                  @change="setIsAllStatus"
                >
                  <a-select-option :value="1">
                    全部
                  </a-select-option>
                  <a-select-option :value="2">
                    可用
                  </a-select-option>
                  <a-select-option :value="3">
                    不可用
                  </a-select-option>
                </a-select>
              </a-tooltip>
            </a-col>
            <a-col
              v-if="isShowProjectStatus"
              :span="12"
            >
              <a-tooltip placement="top">
                <template slot="title">
                  <span>项目状态筛选</span>
                </template>
                <a-select
                  v-model="status"
                  style="width: 100%"
                  placeholder="请选择项目状态"
                  @change="handleChange"
                >
                  <a-select-option :value="1">
                    全部
                  </a-select-option>
                  <a-select-option :value="2">
                    非竣工项目
                  </a-select-option>
                  <a-select-option :value="3">
                    竣工项目
                  </a-select-option>
                </a-select>
              </a-tooltip>
            </a-col>
          </a-row>
          <a-tree
            ref="treeRefs"
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :tree-data="gData"
            :getPopupContainer="(triggerNode)=> triggerNode.parentNode"
            :replace-fields="replaceFields"
            class="treeWidth"
            :selected-keys="selectedKeys"
            style="max-height: 260px;overflow: auto"
            @expand="onExpand"
            @select="selectNode"
          >
            <template
              :slot="replaceFields.title"
              slot-scope="scopes"
            >
              <span v-if="scopes.orgName.indexOf(redValue) > -1">
                {{ scopes.orgName.substr(0, scopes.orgName.indexOf(redValue)) }}
                <span style="color: #f50">{{ redValue }}</span>
                {{
                    scopes.orgName.substr(scopes.orgName.indexOf(redValue) + redValue.length)
                }}
              </span>
              <span v-else>{{ scopes.orgName }}</span>
            </template>
          </a-tree>
        </a-spin>
      </div>
    </div>
    <!-- 这里本身就有交互问题,框架有bug 嵌入输入框 会自动失去焦点，后期如果需要解决 可以自己写下拉 使用v-clickOutside触发点击元素外事件-->
    <!--    <a-popover v-model="visible" trigger="click" placement="bottom"-->
    <!--      :overlay-class-name="!appendToBody ? `${domClass} popC pop` : `${domClass} pop`" arrow-point-at-center-->
    <!--      :get-popup-container="!appendToBody ? (triggerNode) => triggerNode.parentNode : null">-->
    <!--      <template slot="content">-->
    <!--        <a-spin v-show="!disabled" :spinning="spinning">-->
    <!--          <a-row :gutter="[10, 0]" style="padding: 0 15px">-->
    <!--            <a-col :span="12">-->
    <!--              <a-tooltip placement="top">-->
    <!--                <template slot="title">-->
    <!--                  <span>组织状态筛选</span>-->
    <!--                </template>-->
    <!--                <a-select v-model="enable" style="width: 100%" placeholder="请选择组织状态" @change="setIsAllStatus">-->
    <!--                  <a-select-option :value="1">-->
    <!--                    全部-->
    <!--                  </a-select-option>-->
    <!--                  <a-select-option :value="2">-->
    <!--                    可用-->
    <!--                  </a-select-option>-->
    <!--                  <a-select-option :value="3">-->
    <!--                    不可用-->
    <!--                  </a-select-option>-->
    <!--                </a-select>-->
    <!--              </a-tooltip>-->
    <!--            </a-col>-->
    <!--            <a-col v-if="isShowProjectStatus" :span="12">-->
    <!--              <a-tooltip placement="top">-->
    <!--                <template slot="title">-->
    <!--                  <span>项目状态筛选</span>-->
    <!--                </template>-->
    <!--                <a-select v-model="status" style="width: 100%" placeholder="请选择项目状态" @change="handleChange">-->
    <!--                  <a-select-option :value="1">-->
    <!--                    全部-->
    <!--                  </a-select-option>-->
    <!--                  <a-select-option :value="2">-->
    <!--                    非竣工项目-->
    <!--                  </a-select-option>-->
    <!--                  <a-select-option :value="3">-->
    <!--                    竣工项目-->
    <!--                  </a-select-option>-->
    <!--                </a-select>-->
    <!--              </a-tooltip>-->
    <!--            </a-col>-->
    <!--          </a-row>-->
    <!--          <a-tree ref="treeRefs" :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" :tree-data="gData"-->
    <!--            :replace-fields="replaceFields" class="treeWidth" :selected-keys="selectedKeys" style="max-height: 260px;"-->
    <!--            @expand="onExpand" @select="selectNode">-->
    <!--            <template :slot="replaceFields.title" slot-scope="scopes">-->
    <!--              <span v-if="scopes.orgName.indexOf(redValue) > -1">-->
    <!--                {{ scopes.orgName.substr(0, scopes.orgName.indexOf(redValue)) }}-->
    <!--                <span style="color: #f50">{{ redValue }}</span>-->
    <!--                {{-->
    <!--                    scopes.orgName.substr(scopes.orgName.indexOf(redValue) + redValue.length)-->
    <!--                }}-->
    <!--              </span>-->
    <!--              <span v-else>{{ scopes.orgName }}</span>-->
    <!--            </template>-->
    <!--          </a-tree>-->
    <!--        </a-spin>-->
    <!--      </template>-->
    <!--      <a-input ref="iptRefs" :value="text" placeholder="请选择" class="inpWidth" :disabled="disabled"-->
    <!--        :allow-clear="text && allowClear && !disabled" @change="onChange" @blur="blurVal" />-->
    <!--      &lt;!&ndash;      style="padding-right: 26px"&ndash;&gt;-->
    <!--    </a-popover>-->
  </div>
</template>

<script>
import { queryProjectTree, queryProjectTreeByCondition } from '@/api/commons'
import { getProjectsDel } from '@/api/project/projects'

// 获取父节点key值
const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.childTree) {
      if (node.childTree.some((item) => item.orgId === key)) {
        parentKey = node.orgId
      } else if (getParentKey(key, node.childTree)) {
        parentKey = getParentKey(key, node.childTree)
      }
    }
  }
  return parentKey
}
let timer = null
export default {
  name: 'TreeSelect',
  props: {
    /**
     * 弹窗默认挂载父节点
     * */
    appendToBody: {
      type: Boolean,
      default: false
    },
    /**
     * 额外的扩展查询条件
     * */
    extraQuery: {
      type: Object,
      default: () => {}
    },
    /**
     * 是否是特殊页面需要的树
     * */
    isSpecialTree: {
      type: Boolean,
      default: false
    },
    /**
     * 是否搜索页面
     *  搜索页需要隐藏项目状态 表单页不需要 默认为false
     * */
    isSearchPage: {
      type: Boolean,
      default: false
    },
    /**
     *  text适用于表单28px  其他适用于其他页面 需要32px
     * */
    type: {
      type: [String, Object],
      default: 'text'
    },
    /**
     * 禁用
     * */
    disabled: {
      type: Boolean,
      default: false
    },
    // 绑定的值
    // 支持v-model
    value: {
      type: [String, Number, Array, Object],
      default: ''
    },
    /**
     * 是否需要根据权限获取组织
     * */
    isNeedAuth: {
      type: Boolean,
      default: true
    },
    /**
     * 是否传西南公司id，即不走权限
     * */
    southwestCompany: {
      type: Boolean,
      default: false
    },
    /**
     *  是否需要展示项目
     * */
    isShowProject: {
      type: Boolean,
      default: true
    },
    /**
     * 是否需要查询项目详情信息
     * */
    isQueryProjecDetail: {
      type: Boolean,
      default: true
    },
    /**
     * 项目状态集合（0：立项中/1：施工准备阶段/2：在建/3：停工/4：停缓建/5：维保期/6：维保期截止）
     * */
    statusSet: {
      type: Array,
      default: () => [1, 2, 3, 4, 5, 6]
    },
    /**
     * 只允许选择最后一级
     * */
    checkStrictly: {
      type: Boolean,
      default: false
    },
    /**
     * 页面需要的字段标签，传[]返回所有层级
     * */
    needTags: {
      type: Array,
      default: () => {
        return ['BC', 'PD']
      }
    },
    // 是否允许清除
    allowClear: {
      type: Boolean,
      default: true
    },
    // 是否默认选择第一个
    isAutoSelectFirst: {
      type: Boolean,
      default: false
    },
    //默认第一个不是项目，不取orgId
    notIsAutoSelectFirst: {
      type: Boolean,
      default: false
    },
    /**
     *  替换v-model 绑定值 返回选中的数组
     * */
    replaceModel: {
      type: Boolean,
      default: false
    },
    /**
     *  是否显示项目状态筛选条件
     * */
    isShowProjectStatus: {
      type: Boolean,
      default: false
    },
    /**
     * 不过滤的业务id
     * */
    excludeBusinessSet: {
      type: Array,
      default: () => []
    },
    /**
     * 项目层级v-model返回orgId
     * */
    isNeedOrgId: {
      type: Boolean,
      default: false
    },
    /**
     * 是否允许选择本机及下级
     * */
    isAllowNnect: {
      type: Boolean,
      default: false
    },
    // 不显示项目
    hideProject: {
      type: Boolean,
      default: false
    },
    // 默认搜索值
    defaultSearchValue: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    // 强制清空默认值 defaultSearchValue
    isClear: {
      type: Boolean,
      default: false
    },
    // 是否在与根节点同一级显示 其他
    showOther: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      inputKey: new Date() + '1', //给ipnut一个key 避免无法删除完的问题
      loadingSpin: false,
      status: 2,
      selectedKeys: [],
      replaceFields: {
        title: 'orgName',
        key: 'orgId',
        children: 'childTree'
      },
      visible: false,
      enable: 2, // 是否展示所有组织
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      gData: [], //带搜索的树数据
      dataList: [], // 整棵树数据
      selectValue: [],
      cacheList: [],
      authOrgData: [],
      currentTree: [],
      isChange: false,
      currentTag: 'CO',
      searchStatusSet: [1, 2, 3, 4],
      spinning: false,
      domClass: 'domClass',
      iptClass: 'iptClass',
      redValue: '',
      cacheTree: [],
      isInit: true
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          if (this.isSearchPage) {
            document.querySelector(`.${this.domClass} .treeWidth`).style.minWidth = '260px'
          } else {
            document.querySelector(`.${this.domClass} .treeWidth`).style.minWidth = document.querySelector(`.${this.iptClass} .inpWidth`).clientWidth + 'px'
          }

          // const modal = document.querySelector('.ant-modal-body .treeOrgBox')
          // if (modal) {
          //   // popover 和 input 宽度一样 如果是弹窗 取弹窗里面的宽度
          //   document.querySelector('.treeWidth').style.minWidth = document.querySelector('.ant-modal-body .inpWidth').clientWidth + 'px'
          // } else {
          //   // popover 和 input 宽度一样
          //   document.querySelector('.treeWidth').style.minWidth = document.querySelector('.inpWidth').clientWidth + 'px'
          // }
        })
      } else {
        this.searchValue = ''
        this.redValue = ''
        // this.searchStatusSet = [1,2,3,4]
        // // 还原数据
        // this.enable = 2
        // if (this.isSearchPage) {
        //   this.getOrgTree(true)
        // } else {
        //   this.setIsAllStatus()
        // }
        // 若果有选择 需要还原选择的
        if (this.cacheList.length > 0) {
          this.selectValue = this.cacheList
        } else {
          this.searchValue = ''
        }
      }
    },
    value(newVal) {
      if (timer) {
        clearInterval(timer)
      }
      if (!newVal) {
        this.selectedKeys = []
        //支持搜索重置
        this.clearInput()
      } else {
        if (this.gData.length !== 0) {
          this.setValue(newVal)
        } else {
          // 定时器监听 以防接口缓慢
          this.sleep(newVal)
        }
      }
    },
    isClear(val) {
      if (val) {
        this.clearInput()
      }
    }
  },
  computed: {
    //显示文本
    text() {
      if (this.isChange) {
        return this.searchValue
      }
      if (this.selectValue.length) {
        const arrText = this.selectValue.map((item) => {
          return item.projectName || item.orgName
        })
        return arrText.join('/')
      }
      return this.searchValue
    },
    queryData() {
      let orgId = ''
      if (this.isNeedAuth) {
        if (this.southwestCompany || this.disabled) {
          orgId = '53085e2c9f1f4685801ef31994f57c49'
        } else {
          orgId = this.$userInfo().currentPost.id
        }
      } else {
        // 固定的西南公司id
        orgId = '53085e2c9f1f4685801ef31994f57c49'
      }
      //southwestCompany
      let statusSet = []
      if (this.isSearchPage) {
        statusSet = new Set([...this.searchStatusSet])
      } else {
        statusSet = this.statusSet
      }

      return {
        orgId,
        statusSet: [...statusSet],
        ...this.extraQuery,
        excludeBusinessSet: this.excludeBusinessSet
      }
    }
  },
  mounted() {
    // 设置动态class是弹窗唯一 以确保弹窗宽度和input一致
    let idx = sessionStorage.getItem('dId') || 0
    this.domClass = 'domClass' + idx
    this.iptClass = 'iptClass' + idx
    idx++
    sessionStorage.setItem('dId', idx)

    if (this.$userInfo().currentPost) {
      this.currentTag = this.$userInfo().currentPost.code
    }
    this.getOrgTree()
  },
  methods: {
    sleep(newVal) {
      timer = setInterval(() => {
        if (this.gData.length) {
          this.setValue(newVal)
          console.log('正在跑')
          clearInterval(timer)
        }
      }, 10)
    },
    setValue(newVal) {
      if (this.cacheTree.length === 0) {
        return false
      }
      this.dataList = []

      // 重新1维生成数据 防止 数据不存在
      this.generateList(this.cacheTree)
      this.selectValue = this.getParentDataByValue(newVal).reverse()
      this.selectedKeys = [this.selectValue[this.selectValue.length - 1].orgId]
      this.expandedKeys = this.getExpendKey(this.selectValue[this.selectValue.length - 1].orgId, this.dataList)
      this.setNeedtags()

      this.$emit('select', this.selectValue)
      if (this.isShowProject && this.isQueryProjecDetail) {
        if (this.selectValue[this.selectValue.length - 1].projectId) {
          this.getProjectsDel(this.selectValue[this.selectValue.length - 1].projectId)
        }
      }
    },
    out() {
      this.blurVal()
      this.visible = false
    },
    handleChange(val) {
      if (this.status == 1) {
        //全部
        this.searchStatusSet = [1, 2, 3, 4, 5, 6]
      } else if (this.status == 2) {
        //非竣工项目
        this.searchStatusSet = [1, 2, 3, 4]
      } else {
        //竣工项目
        this.searchStatusSet = [5, 6]
      }
      this.clearInput()
      this.getOrgTree(false, () => {
        // this.$emit('proStatusChange')
      })
    },
    /**
     * 是否展示所有组织
     * */
    setIsAllStatus(val) {
      // this.clearInput()
      //默认展示全部可用数据
      let result = []

      if (this.enable == 1) {
        // 展示全部
        const arr = JSON.parse(JSON.stringify(this.dataList))
        result = this.generateTree(arr)
      } else if (this.enable == 2) {
        // 展示可用
        const arr2 = JSON.parse(JSON.stringify(this.dataList))
        const arr = arr2.filter((item) => item.enable == 1)
        result = this.generateTree(arr)
      } else {
        // 不可用 这里产品设计脑残
        const arr = this.dataList.filter((item) => item.enable != 1)
        let newArr = []
        arr.forEach((item) => {
          const arr2 = this.getParentDataByValue(item.orgId)
          if (arr2 && arr2.length) {
            arr2.forEach((ele) => {
              if (!newArr.find((z) => z.orgId === ele.orgId)) {
                newArr.push(ele)
              }
            })
          }
        })
        result = this.generateTree(newArr)
      }
      this.clearInput()
      this.gData = result

      // this.$emit('orgStatusChange')
      // this.autoShow()
    },
    /**
     * 根据value获取父级数据 0fcb2d91bf6e4f5b9e15f17217921f71
     * id可能是orgId 也可能是projectId  设计如此
     * */
    getParentDataByValue(id) {
      let arr = []
      const obj = this.dataList.find((item) => item.orgId == id || item.projectId == id)
      if (obj) {
        arr.push(obj)
        if (obj.parentId) {
          arr = arr.concat(this.getParentDataByValue(obj.parentId, this.dataList))
        }
      }
      return arr
    },
    /**
     * 获取父级数据
     * */
    getParentData(node) {
      let arr = []
      if (node.$parent.dataRef) {
        arr.push(node.$parent.dataRef)
        if (node.$parent) {
          arr = arr.concat(this.getParentData(node.$parent))
        }
      }
      return arr
    },
    /**
     *  设置需要返回的标签
     * */
    setNeedtags() {
      if (this.needTags && this.needTags.length) {
        const newArr = []
        this.selectValue.forEach((item) => {
          if (this.needTags.includes(item.tageCode)) {
            newArr.push(item)
          }
        })
        this.selectValue = newArr
      }
    },
    /**
     * 选中节点触发
     * */
    selectNode(selectedKeys, { node }) {
      this.isChange = false
      this.isInit = false
      if (this.value == node.dataRef.orgId || this.value == node.dataRef.projectId) {
        this.visible = false
        return
      }
      const arr = this.getParentData(node).reverse()
      arr.push(node.dataRef)
      this.selectValue = arr
      this.setNeedtags()
      this.cacheList = JSON.parse(JSON.stringify(this.selectValue))
      // 支持v-model
      if (this.selectValue.length) {
        if (this.isNeedOrgId) {
          this.$emit('input', this.selectValue[this.selectValue.length - 1].orgId)
          // 针对于搜索 v-decorator 绑定值
          this.$emit('change', this.selectValue[this.selectValue.length - 1].orgId)
        } else {
          this.$emit('input', this.selectValue[this.selectValue.length - 1].projectId || this.selectValue[this.selectValue.length - 1].orgId)
          // 针对于搜索 v-decorator 绑定值
          this.$emit('change', this.selectValue[this.selectValue.length - 1].projectId || this.selectValue[this.selectValue.length - 1].orgId)
        }
      }
      // 只用于 主动触发选择 才做的事件
      this.$emit('handleChange', this.selectValue)
      this.$emit('select', this.selectValue)

      if (this.isShowProject && this.isQueryProjecDetail) {
        if (this.selectValue[this.selectValue.length - 1]?.projectId) {
          this.getProjectsDel(this.selectValue[this.selectValue.length - 1].projectId)
        }
      }
      this.visible = false
    },
    /**
     * 树节点展开
     * */
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    /**
     * 输入框失去焦点
     * */
    blurVal() {
      this.isChange = false
      if (!this.isSearchPage && this.cacheList.length) {
        this.selectValue = this.cacheList
      }
    },
    getExpendKey(id, list) {
      let arr = []
      arr.push(id)
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (item.orgId === id) {
          if (item.parentId) {
            arr = arr.concat(this.getExpendKey(item.parentId, list))
          }
          break
        }
      }
      return arr
    },
    /**
     * 搜索框值变更时触发
     * */
    onChange(e) {
      this.isChange = true
      const value = e.target.value
      this.redValue = value
      this.visible = true
      if (!value) {
        this.searchValue = ''
        this.clearInput()
        return
      }
      let expandedKeys = []
      this.dataList.forEach((item) => {
        if (item.orgName.indexOf(value) > -1) {
          const arr = this.getExpendKey(item.orgId, this.dataList)
          expandedKeys.push(...arr)
        }
        return null
      })
      expandedKeys = Array.from(new Set(expandedKeys))
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    /**
     * 转化为1维数组
     * */
    generateList(data) {
      const newData = JSON.parse(JSON.stringify(data))
      for (let i = 0; i < newData.length; i++) {
        const node = newData[i]
        if (this.hideProject && node.tageCode === 'PD') {
          return
        }
        this.dataList.push(node)
        if (node.childTree) {
          this.generateList(node.childTree)
        }
      }
    },
    /**
     * 添加ScopedSlots属性到数组里
     * **/
    addScopedSlotsToArr(tree) {
      tree.forEach((item) => {
        item.scopedSlots = { title: 'orgName' }
        // if(!this.isSearchPage) {
        //   if (item.enable !== '1') {
        //     item.disabled = true
        //   } else {
        //     item.disabled = false
        //   }
        // }

        if (item.tageCode == 'PD') {
          item.orgName = item.projectName
        } else {
          if (this.checkStrictly && !this.hideProject) {
            item.disabled = true
          }
        }
        if (item.childTree && item.childTree.length) {
          this.addScopedSlotsToArr(item.childTree)
        }
      })
    },
    // 二次递归 只允许选择当前及下级
    addScopedSlotsToArr2(tree, disabled = false) {
      if (['CO', 'BC', 'PD'].includes(this.currentTag)) {
        tree.forEach((item) => {
          if (item.orgId === '1') {
            return
          }
          if (!item.disabled) {
            if (this.currentTag != item.tageCode && !disabled) {
              // if(this.isAllowNnect) {
              item.disabled = true
              // }

              if (item.childTree && item.childTree.length) {
                this.addScopedSlotsToArr2(item.childTree, false)
              }
            } else {
              if (item.childTree && item.childTree.length) {
                this.addScopedSlotsToArr2(item.childTree, true)
              }
            }
          }
        })
      }
    },
    getFirstData(treeData) {
      let arr = []
      arr.push(treeData[0])
      if (treeData[0].childTree && treeData[0].childTree.length) {
        arr = arr.concat(this.getFirstData(treeData[0].childTree))
      }
      return arr
    },
    /**
     * 生成新的树
     * */
    generateTree(dataList) {
      let nodeList = JSON.parse(JSON.stringify(dataList))
      if (!nodeList || nodeList.length === 0) {
        return []
      }
      nodeList.forEach((item) => {
        item.childTree = []
      })
      //生成节点的map
      const nodeMap = nodeList.reduce((acc, cur) => {
        acc[cur.orgId] = cur
        return acc
      }, {})
      const result = []
      nodeList.forEach((item) => {
        if (!item.parentId) {
          result.push(item)
          return
        }
        const parentNode = nodeMap[item.parentId]
        parentNode.childTree = [...(parentNode.childTree || []), item]
      })
      return result
    },
    /**
     * 获取组织树
     * */
    async getOrgTree(isBack = false, callback) {
      this.spinning = true
      this.loadingSpin = true
      let request = null
      if (!this.isSpecialTree) {
        request = queryProjectTree
      } else {
        request = queryProjectTreeByCondition
      }

      try {
        let data = {
          ...this.queryData
        }
        await request(data).then((res) => {
          let resData = [res.data]
          if (this.showOther) {
            let obj = {
              enable: '1',
              orgName: '其他',
              orgId: '1',
              parentId: null,
              projectId: 1,
              projectName: '其他',
              tageCode: 'PD',
              childTree: null
            }
            resData.unshift(obj)
          }
          //增加自定义slot
          this.addScopedSlotsToArr(resData)
          if (this.isSearchPage || this.isAllowNnect) {
            // 根据权限禁用 搜索页面只允许选择本级及下级
            this.addScopedSlotsToArr2(resData)
          }

          this.cacheTree = JSON.parse(JSON.stringify(resData))
          // 转化为1维数组 只为展示红色文字
          if (!isBack) {
            this.dataList = []
            this.generateList(resData)
            this.dataList.forEach((item) => {
              item.childTree = []
            })
          }
          this.setIsAllStatus()

          //默认展开到分公司层级
          let topLevelId = resData.filter((v) => !v.parentId)
          this.expandedKeys.push(topLevelId[0].orgId)

          if (!isBack) {
            this.autoShow()
          }
          this.spinning = false
          callback && callback()
          setTimeout(() => {
            this.loadingSpin = false
          }, 500)
        })
      } catch (e) {
        this.loadingSpin = false
        this.spinning = false
      }
    },
    // 自动回显
    autoShow() {
      try {
        if (this.defaultSearchValue !== '') {
          this.selectValue = this.getParentDataByValue(this.defaultSearchValue).reverse()
        }
        if (this.isAutoSelectFirst && !this.disabled) {
          // 默认填充第一条数据
          this.selectValue = this.getFirstData(this.gData)
          this.setNeedtags()
          this.cacheList = JSON.parse(JSON.stringify(this.selectValue))
          if (this.selectValue.length) {
            this.selectedKeys = [this.selectValue[this.selectValue.length - 1].orgId]
            this.expandedKeys = this.getExpendKey(this.selectValue[this.selectValue.length - 1].orgId, this.dataList)
          }
          if (this.notIsAutoSelectFirst && !this.selectValue[this.selectValue.length - 1].projectId) {
            this.$emit('input', this.selectValue[this.selectValue.length - 1].projectId)
          } else {
            this.$emit('input', this.selectValue[this.selectValue.length - 1].projectId || this.selectValue[this.selectValue.length - 1].orgId)
            this.$emit('select', this.selectValue)
          }
          if (this.isShowProject && this.isQueryProjecDetail) {
            if (this.selectValue[this.selectValue.length - 1].projectId) {
              this.getProjectsDel(this.selectValue[this.selectValue.length - 1].projectId)
            }
          }
        }
        if (this.value) {
          this.selectValue = this.getParentDataByValue(this.value).reverse()
          this.setNeedtags()
          this.cacheList = JSON.parse(JSON.stringify(this.selectValue))
          if (this.selectValue.length) {
            this.selectedKeys = [this.selectValue[this.selectValue.length - 1].orgId]
            this.expandedKeys = this.getExpendKey(this.selectValue[this.selectValue.length - 1].orgId, this.dataList)
          }
          if (this.notIsAutoSelectFirst && !this.selectValue[this.selectValue.length - 1].projectId) {
            this.$emit('input', this.selectValue[this.selectValue.length - 1].projectId)
          } else {
            this.$emit('input', this.selectValue[this.selectValue.length - 1].projectId || this.selectValue[this.selectValue.length - 1].orgId)
            this.$emit('select', this.selectValue)
          }
          if (this.isShowProject && this.isQueryProjecDetail) {
            if (this.selectValue[this.selectValue.length - 1].projectId) {
              this.getProjectsDel(this.selectValue[this.selectValue.length - 1].projectId)
            }
          }
        }
      } catch (error) {
        console.log(error)
      }
    },
    //获取项目详情
    getProjectsDel(projectId) {
      if (!projectId) {
        return
      }
      getProjectsDel({ projectId }).then((res) => {
        // 向上派发 项目详情
        this.$emit('getProjectInfo', res.data)
      })
    },
    clearInput() {
      if (this.isSearchPage) {
        this.selectedKeys = []
        this.redValue = ''
        this.cacheList = []
        this.selectValue = []
        this.$emit('input', '')
        this.$emit('change', '')
        this.$emit('select', [])
      } else {
        this.selectedKeys = []
        this.selectValue = []
        this.redValue = ''
      }
    }
  },
  directives: {
    clickOutside: {
      // 初始化指令
      bind(el, binding, vnode) {
        function clickHandler(e) {
          // 这里判断点击的元素是否是本身，是本身，则返回
          if (el.contains(e.target)) {
            return false
          }
          // 判断指令中是否绑定了函数
          if (binding.expression) {
            // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
            binding.value(e)
          }
        }

        // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
        el.__vueClickOutside__ = clickHandler
        document.addEventListener('click', clickHandler)
      },
      update() {},
      unbind(el, binding) {
        // 解除事件监听
        document.removeEventListener('click', el.__vueClickOutside__)
        delete el.__vueClickOutside__
      }
    }
  }
}
</script>

<style lang="less">
/*.popC {*/
/*  top: 32px !important;*/
/*  left: 0 !important;*/
/*}*/

.pop {
  .ant-select:not(.ant-select-disabled) .ant-select-selection {
    background-color: #fff !important;
    border: 1px solid #d9d9d9 !important;
  }
}

.treeOrgBox {
  position: relative;
  /*display: flex;*/
  /*margin: 6px 0;*/
  flex: 1;
  .selectTree {
    top: 40px;
    left: 0;
    position: absolute;
    background-color: #fff;
    box-shadow: 0 2px 8px #00000026;
    z-index: 999;
  }
  .searchIcon {
    position: absolute;
    top: 12px;
    right: 10px;
    z-index: 100;
    font-size: 16px;
    /*cursor: pointer;*/
    color: #ccc;
  }

  .searchIcon2 {
    position: absolute;
    top: 8px;
    right: 10px;
    z-index: 100;
    font-size: 16px;
  }

  .closeIcon {
    position: absolute;
    top: 12px;
    right: 30px;
    z-index: 100;
    font-size: 16px;
    cursor: pointer;
  }
}

.inpWidth {
  width: 100%;

  .ant-input-suffix {
    right: 30px !important;
  }
}

.dtext {
  .inpWidth {
    height: 28px !important;
  }
}

.baseText {
  .inpWidth {
    height: 32px !important;
  }
}

.pop {
  li.ant-tree-treenode-disabled > span:not(.ant-tree-switcher),
  li.ant-tree-treenode-disabled > .ant-tree-node-content-wrapper,
  li.ant-tree-treenode-disabled > .ant-tree-node-content-wrapper span {
    color: rgba(0, 0, 0, 0.6);
    cursor: default;
  }

  /*top: 18px!important;*/

  .ant-popover-arrow {
    /*display: none!important;*/
  }

  .ant-popover-inner-content {
    box-sizing: border-box;
    padding: 10px 0;
    position: relative;

    .eye {
      position: absolute;
      right: 15px;
      top: 5px;
      font-size: 16px;
      cursor: pointer;
    }

    .treeWidth {
      box-sizing: border-box;
      padding: 0 10px;
      overflow: auto;
    }
  }
}
</style>
